﻿using Prism.Commands;
using Prism.Events;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using ZoneLinePacking.Common;
using ZoneLinePacking.Core;
using ZoneLinePacking.Core.EventArgs;
using ZoneLinePacking.Models.Package;
using ZoneLinePacking.Services.DB;
using ZoneLinePacking.Services.Message;
using ZoneLinePacking.ViewModelBase;

namespace ZoneLinePacking.ViewModels.Dialogs {
    public class ContinueBoxUpDialogViewModel : DialogViewModel {

        public ContinueBoxUpDialogViewModel(
            IRegionManager regionManager, 
            IDialogService dialog, 
            IEventAggregator eventAggregator, 
            IMessageService message, 
            IDbOperate<IFreeSqlMainContext> mainDbOperate) 
            : base(regionManager, dialog, eventAggregator, message, mainDbOperate) {


        }

        #region Props
        private string _boxCode = "";

        public string BoxCode {
            get { return _boxCode; }
            set { _boxCode = value; base.RaisePropertyChanged(); }
        }

        private ObservableCollection<PackageTempModel> _inPackageAbsLst = new ObservableCollection<PackageTempModel>();

        public ObservableCollection<PackageTempModel> InPackageAbsLst {
            get { return _inPackageAbsLst; }
            set { _inPackageAbsLst = value; base.RaisePropertyChanged(); }
        }
        #endregion

        #region Commands
        public DelegateCommand SearchCmd => new DelegateCommand(() => {
            if (BoxCode != null) {
                InPackageAbsLst.Clear();
                var list = _mainDbOperate.GetModelList<PackageResult>(o => o.BoxCode == BoxCode);
                if (list != null && list.Count > 0) {
                    var packageTempModels = new List<PackageTempModel>();
                    foreach (var item in list) {
                        var packageTempModel = new PackageTempModel() {
                            AbsCode = item.AbsCode,
                            Code = item.Code,
                            Brand = item.Brand,
                            LeftRight = item.LeftRight,
                            PrintTime = item.PrintTime,
                            BoxCode = item.BoxCode,
                            PackageTime = item.PackageTime,
                            Model = item.Model,
                        };
                        packageTempModels.Add(packageTempModel);
                    }
                    InPackageAbsLst.AddRange(packageTempModels);
                }
            }
        });

        public DelegateCommand ConfirmCommand => new DelegateCommand(() => {

            if (string.IsNullOrEmpty(BoxCode)) {
                _message.Error("请输入装箱码！");
                return;
            }

            var tempList = _mainDbOperate.GetModelList<PackageTempModel>(o => true);
            if (tempList.Count > 0) {
                _message.Error("装箱列表中存在尚未装箱的产品！");
                return;
            }

            if (InPackageAbsLst.Any(o => o.Brand != Cache.CurWorkProduct.CustomerName)) {
                _message.Error("当前列表中的产品与选择的装箱产品【品牌不匹配】！");
                return;
            }

            if (InPackageAbsLst.Any(o => !string.IsNullOrEmpty(o.Model) && o.Model != Cache.CurWorkProduct.Model)) {
                _message.Error("当前列表中的产品与选择的装箱产品【型号不匹配】！");
                return;
            }

            if (InPackageAbsLst.Any(o => o.LeftRight != (int)Cache.CurWorkProduct.WorkDirection)) {
                _message.Error("当前列表中的产品与选择的装箱产品【左右方向不匹配】！");
                return;
            }
            var ask = _message.Ask($"请确认该箱码中的{InPackageAbsLst.Count}个产品是否继续装箱？");
            if (ask == System.Windows.MessageBoxResult.OK) {
                var list = _mainDbOperate.GetModelList<PackageResult>(o => o.BoxCode == BoxCode);
                var res = false;
                if (InPackageAbsLst.Count > 0) {
                    res = _mainDbOperate.AddModels<PackageTempModel>(InPackageAbsLst.ToList());
                    LogManager.Warn($"继续装箱，新增PackageTempModel临时表数据，rls={res}，count={InPackageAbsLst.Count}");
                }

                if (res) {
                    res = _mainDbOperate.DeleteModel<PackageResult>(o => o.BoxCode == BoxCode);
                    LogManager.Warn($"继续装箱，清除PackageResult装箱表数据，rls={res}，count={InPackageAbsLst.Count}");
                }
                OnDialogClosed(ButtonResult.OK);
            }
            OnDialogClosed(ButtonResult.Cancel);
        });

        public DelegateCommand CancelCommand => new DelegateCommand(() => {
            OnDialogClosed(ButtonResult.Cancel);
        });

        public bool CanClosed { get; set; }

        public override bool CanCloseDialog() {
            return CanClosed;
        }

        public override void OnDialogClosed(ButtonResult button) {
            CanClosed = true;
            _eventAggregator.GetEvent<PubSubEventArgs>().Unsubscribe(OnEventReceived);
            base.OnDialogClosed(button);
        }

        public override void OnDialogOpened(IDialogParameters parameters) {
            _eventAggregator.GetEvent<PubSubEventArgs>().Subscribe(OnEventReceived);
            base.OnDialogOpened(parameters);
        }


        private void OnEventReceived(MessageData data) {
            if (data.Code == nameof(MainPackingViewModel)) {
                if (data.Parameters.ContainsKey(MainPackingViewModel._scanBarCodeKey)) {
                    string scanBarCode = data.Parameters.GetValue<string>(MainPackingViewModel._scanBarCodeKey);
                    this.BoxCode = scanBarCode;
                }
            }
        }
        #endregion



    }
}
